package cn.caidabao.gb.util;

import cn.caidabao.gb.bean.QueryObject;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class MessageObjectUtil {
    private final static DateTimeFormatter timeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");

    private static Integer offSet = 0;
    private static synchronized String getSn(){
        offSet = offSet%100000000+1;
        return String.valueOf(offSet);
    }
    private static String generateCatalogXml(String deviceId,String sn){
        return String.format("<?xml version=\"1.0\" encoding=\"GB2312\"?>\n" +
                "<Query>\n" +
                "<CmdType>Catalog</CmdType>\n" +
                "<DeviceID>%s</DeviceID>\n" +
                "<SN>%s</SN>\n" +
                "</Query>",deviceId,sn);
    }

    private static String generateRecordInfoXml(String channelId,String startTime,String endTime,String sn){
        return String.format("<?xml version=\"1.0\" encoding=\"GB2312\"?>\n" +
                "<Query>\n" +
                "<CmdType>RecordInfo</CmdType>\n" +
                "<DeviceID>%s</DeviceID>\n" +
                "<SN>%s</SN>\n" +
                "<StartTime>%s</StartTime>\n" +
                "<EndTime>%s</EndTime>\n" +
                "</Query>",channelId,sn,startTime,endTime);
    }

    public static QueryObject generateCatalogObject(String deviceId){
        QueryObject queryObject = new QueryObject();
        queryObject.setCmdType("Catalog");
        String sn = getSn();
        queryObject.setContent(generateCatalogXml(deviceId,sn));
        queryObject.setSn(sn);
        queryObject.setDeviceId(deviceId);
        queryObject.setCallBackId(CallBackIdUtils.generateDeviceInfoMessageCallBackId(deviceId,sn));
        return queryObject;
    }

    public static QueryObject generateRecordInfoObject(String channelId, LocalDateTime startTime,LocalDateTime endTime){
        QueryObject queryObject = new QueryObject();
        queryObject.setCmdType("RecordInfo");
        String sn = getSn();
        queryObject.setContent(generateRecordInfoXml(channelId,timeFormatter.format(startTime),timeFormatter.format(endTime),sn));
        queryObject.setSn(sn);
        queryObject.setDeviceId(channelId);
        queryObject.setCallBackId(CallBackIdUtils.generateRecordInfoMessageCallBackId(channelId,sn));
        return queryObject;
    }
}
